package LawsonTransformJava.xref;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.TreeMap;

import LawsonTransformJava.dao.DAOAccessDB;


/**
 * This class reads cross reference data from an Access DB and maps in memory for retrieval through the {@link CrossRef.xlate} method
 * @author edavis
 *
 */
public class CrossRef {

	protected static boolean errFound = false;

	String XLATE_ERROR = "CROSSREF";  //Default translation error - overridden in the child object
	TreeMap<String, String> values = new TreeMap<String, String>();  //Lookup mapping
	protected boolean allowBlanks = false;  //Allow blanks to be returned - overridden in the child object if allowed
	protected DAOAccessDB xref = new DAOAccessDB();
	protected Statement stmt = null;
	protected ResultSet rslt = null;
	

	/**
	 * This is the method that receives a lookup value and returns the appropriate translation value
	 * 
	 * @param lookup	The old value you want looked up
	 * @return			{@link String} - The new translated value
	 */
	public String xlate(String lookup) {
		//Strip out Quotes
		String strip = lookup.replaceAll("\"", "");
		//If lookup value is blank coming in, then pass it back out without a lookup
		if (strip.equals(""))
			return strip;

		//Value found
		String newX = (String)values.get(strip);

		//Lookup value; if not found send back blanks if allowed otherwise send XLATE_ERROR and flag errFound
		if (allowBlanks)
			return (newX==null?"":newX);
		else {
			if (newX==null) {
				//Set Error Flag
				errFound = true;
				return XLATE_ERROR + "_" + lookup.replaceAll("\"", "");
			} else
			return newX;
		}
	}

	protected String stripQuotes(String lookup) {
		//Strip out Quotes
		return lookup.replaceAll("\"", "");
	}

	public static boolean isError() {
		return errFound;
	}
	
	public static void resetError() {
		//Reset errFound
		errFound = false;
	}
	
	public void close() throws SQLException, IOException {
		//Release the resources
		rslt.close();
		stmt.close();
		xref.close();
	}
}
